package com.ruoyi.web.controller.teaching;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.teaching.domain.TeachingClasses;
import com.ruoyi.teaching.domain.TeachingClassesSchedule;
import com.ruoyi.teaching.domain.TeachingClassesStudents;
import com.ruoyi.teaching.service.ITeachingClassesScheduleService;
import com.ruoyi.teaching.service.ITeachingClassesService;
import com.ruoyi.teaching.service.ITeachingClassesStudentsService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.teaching.domain.TeachingClassesScheduleTemplate;
import com.ruoyi.teaching.service.ITeachingClassesScheduleTemplateService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 排课模板Controller
 *
 * @author William
 * @date 2022-10-19
 */
@Controller
@RequestMapping("/teaching/template")
public class TeachingClassesScheduleTemplateController extends BaseController {
    private String prefix = "teaching/template";

    @Autowired
    private ITeachingClassesScheduleTemplateService teachingClassesScheduleTemplateService;

    @Autowired
    private ITeachingClassesScheduleService teachingClassesScheduleService;

    @Autowired
    private ITeachingClassesService teachingClassesService;

    @Autowired
    private ITeachingClassesStudentsService teachingClassesStudentsService;


    @RequiresPermissions("teaching:template:view")
    @GetMapping()
    public String template() {
        return prefix + "/template";
    }

    /**
     * 查询排课模板列表
     */
    @RequiresPermissions("teaching:template:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TeachingClassesScheduleTemplate teachingClassesScheduleTemplate) {
        startPage();
        List<TeachingClassesScheduleTemplate> list = teachingClassesScheduleTemplateService.selectTeachingClassesScheduleTemplateList(teachingClassesScheduleTemplate);
        return getDataTable(list);
    }

    /**
     * 导出排课模板列表
     */
    @RequiresPermissions("teaching:template:export")
    @Log(title = "排课模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TeachingClassesScheduleTemplate teachingClassesScheduleTemplate) {
        List<TeachingClassesScheduleTemplate> list = teachingClassesScheduleTemplateService.selectTeachingClassesScheduleTemplateList(teachingClassesScheduleTemplate);
        ExcelUtil<TeachingClassesScheduleTemplate> util = new ExcelUtil<TeachingClassesScheduleTemplate>(TeachingClassesScheduleTemplate.class);
        return util.exportExcel(list, "排课模板数据");
    }

    /**
     * 新增排课模板
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存排课模板
     */
    @RequiresPermissions("teaching:template:add")
    @Log(title = "排课模板", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(TeachingClassesScheduleTemplate teachingClassesScheduleTemplate) {

        Long classId = teachingClassesScheduleTemplate.getClassId();
        TeachingClasses classes = teachingClassesService.selectTeachingClassesByClassId(classId);
        if (StringUtils.isNull(classes)) {
            return error("班级不存在");
        }
        TeachingClassesStudents query = new TeachingClassesStudents();
        query.setClassId(classId);
        List<TeachingClassesStudents> list = teachingClassesStudentsService.selectTeachingClassesStudentsList(query);
        //不满4人不让排课
        int limitCount = 4;
        if (list.size() < limitCount) {
            return error("该班级不满4人无法排课");
        }

        Date startDate = teachingClassesScheduleTemplate.getStartDate();
        Date endDate = teachingClassesScheduleTemplate.getEndDate();
        if (StringUtils.isNull(startDate)
                || StringUtils.isNull(endDate)) {
            return error("日期不能为空");
        }

        int diffDays = DateUtils.differentDaysByMillisecond(startDate, endDate);
        if (diffDays < 0) {
            return error("日期选择有误");
        }

        String weeks = teachingClassesScheduleTemplate.getWeeks();
        if (StringUtils.isEmpty(weeks)) {
            return error("请选择周几上课");
        }


        //-----先保存到模板表
        teachingClassesScheduleTemplate.setCreateTime(DateUtils.getNowDate());
        teachingClassesScheduleTemplate.setCreateId(getUserId());
        teachingClassesScheduleTemplate.setCreateTime(DateUtils.getNowDate());
        teachingClassesScheduleTemplateService.insertTeachingClassesScheduleTemplate(teachingClassesScheduleTemplate);
        Long templateId = teachingClassesScheduleTemplate.getTemplateId();
        /*
            根据日期重复
            根据重复形式 生成到日程表
        * */
        for (int i = 0; i <= diffDays; i++) {
            Date currentDate = DateUtils.addDays(startDate, i);
            //-----获取当前周几 当前周几 只有在 选择的周几内才能添加到排课表
            String currentWeek = getWeek(currentDate);
            if (weeks.contains(currentWeek)) {
                TeachingClassesSchedule schedule = new TeachingClassesSchedule();
                schedule.setTemplateId(templateId);
                schedule.setSchoolId(classes.getSchoolId());
                schedule.setCourseId(classes.getCourseId());
                schedule.setClassId(classId);
                schedule.setClassName(classes.getClassName());
                schedule.setStartDate(currentDate);
                schedule.setStartTime(teachingClassesScheduleTemplate.getStartTime());
                schedule.setEndTime(teachingClassesScheduleTemplate.getEndTime());
                schedule.setTeacherId(teachingClassesScheduleTemplate.getTeacherId());
                schedule.setTeacherName(teachingClassesScheduleTemplate.getTeacherName());
                schedule.setTopic(teachingClassesScheduleTemplate.getTopic());
                schedule.setCreateId(getUserId());
                schedule.setCreateBy(getLoginName());
                schedule.setCreateTime(DateUtils.getNowDate());
                teachingClassesScheduleService.insertTeachingClassesSchedule(schedule);
            }

        }
        return success();
//        return toAjax();
    }

    public static String getWeek(Date date) {
        String[] weeks = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return weeks[week_index];
    }

    /**
     * 修改排课模板
     */
    @RequiresPermissions("teaching:template:edit")
    @GetMapping("/edit/{templateId}")
    public String edit(@PathVariable("templateId") Long templateId, ModelMap mmap) {
        TeachingClassesScheduleTemplate teachingClassesScheduleTemplate = teachingClassesScheduleTemplateService.selectTeachingClassesScheduleTemplateByTemplateId(templateId);
        mmap.put("teachingClassesScheduleTemplate", teachingClassesScheduleTemplate);
        return prefix + "/edit";
    }

    /**
     * 修改保存排课模板
     */
    @RequiresPermissions("teaching:template:edit")
    @Log(title = "排课模板", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TeachingClassesScheduleTemplate teachingClassesScheduleTemplate) {
        Long classId = teachingClassesScheduleTemplate.getClassId();
        TeachingClasses classes = teachingClassesService.selectTeachingClassesByClassId(classId);
        if (StringUtils.isNull(classes)) {
            return error("班级不存在");
        }
        TeachingClassesStudents query = new TeachingClassesStudents();
        query.setClassId(classId);
        List<TeachingClassesStudents> list = teachingClassesStudentsService.selectTeachingClassesStudentsList(query);
        //不满4人不让排课
        int limitCount = 4;
        if (list.size() < limitCount) {
            return error("该班级不满4人无法排课");
        }

        Date startDate = teachingClassesScheduleTemplate.getStartDate();
        Date endDate = teachingClassesScheduleTemplate.getEndDate();
        if (StringUtils.isNull(startDate)
                || StringUtils.isNull(endDate)) {
            return error("日期不能为空");
        }
        int diffDays = DateUtils.differentDaysByMillisecond(startDate, endDate);
        if (diffDays < 0) {
            return error("日期选择有误");
        }
        String weeks = teachingClassesScheduleTemplate.getWeeks();
        if (StringUtils.isEmpty(weeks)) {
            return error("请选择周几上课");
        }


        //-----先保存到模板表
        teachingClassesScheduleTemplate.setCreateTime(DateUtils.getNowDate());
        teachingClassesScheduleTemplate.setCreateId(getUserId());
        teachingClassesScheduleTemplate.setCreateTime(DateUtils.getNowDate());
        teachingClassesScheduleTemplateService.updateTeachingClassesScheduleTemplate(teachingClassesScheduleTemplate);
        Long templateId = teachingClassesScheduleTemplate.getTemplateId();
          /*
            删除之前根据此模板生成的日程
            请核对已上课的不能删除
        * */
        String scheduleIds = "";
        TeachingClassesSchedule param = new TeachingClassesSchedule();
        param.setTemplateId(templateId);
        List<TeachingClassesSchedule> schedules = teachingClassesScheduleService.selectTeachingClassesScheduleList(param);
        for (TeachingClassesSchedule schedule : schedules) {
            teachingClassesScheduleService.deleteTeachingClassesScheduleByScheduleId(schedule.getScheduleId());
        }

        /*
            根据日期重复
            根据重复形式 生成到日程表
        * */
        for (int i = 0; i <= diffDays; i++) {
            Date currentDate = DateUtils.addDays(startDate, i);
            //-----获取当前周几 当前周几 只有在 选择的周几内才能添加到排课表
            String currentWeek = getWeek(currentDate);
            if (weeks.contains(currentWeek)) {
                TeachingClassesSchedule schedule = new TeachingClassesSchedule();
                schedule.setTemplateId(templateId);
                schedule.setSchoolId(classes.getSchoolId());
                schedule.setCourseId(classes.getCourseId());
                schedule.setClassId(classId);
                schedule.setClassName(classes.getClassName());
                schedule.setStartDate(currentDate);
                schedule.setStartTime(teachingClassesScheduleTemplate.getStartTime());
                schedule.setEndTime(teachingClassesScheduleTemplate.getEndTime());
                schedule.setTeacherId(teachingClassesScheduleTemplate.getTeacherId());
                schedule.setTeacherName(teachingClassesScheduleTemplate.getTeacherName());
                schedule.setTopic(teachingClassesScheduleTemplate.getTopic());
                schedule.setCreateId(getUserId());
                schedule.setCreateBy(getLoginName());
                schedule.setCreateTime(DateUtils.getNowDate());
                teachingClassesScheduleService.insertTeachingClassesSchedule(schedule);
            }
        }
        return success();
//        return toAjax(teachingClassesScheduleTemplateService.updateTeachingClassesScheduleTemplate(teachingClassesScheduleTemplate));
    }

    /**
     * 删除排课模板
     */
    @RequiresPermissions("teaching:template:remove")
    @Log(title = "排课模板", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(teachingClassesScheduleTemplateService.deleteTeachingClassesScheduleTemplateByTemplateIds(ids));
    }
}
